package com.cy.milktea.service.impl;

import com.cy.milktea.common.annotation.SetUserAndTime;
import com.cy.milktea.mapper.UserMapper;
import com.cy.milktea.pojo.User;
import com.cy.milktea.service.UserService;
import com.cy.milktea.utils.PageHelperUtils;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @SetUserAndTime
    @Override
    public int add(User user) {
        //加密
        encrypt(user);
        return userMapper.insert(user);
    }

    @Override
    public int delete(Integer id) {
        return userMapper.delete(id);
    }

    @SetUserAndTime(value = "modify")
    @Override
    public int update(User user) {
        //判断更新的内容是否包含修改密码
        if (StringUtils.hasLength(user.getPassword())) {
            //加密
            encrypt(user);
        } else {
            //防止脏数据
            user.setSalt(null);
        }
        return userMapper.update(user);
    }

    @Override
    public PageInfo<User> query(String name,Integer roleId,Integer valid) {
        return PageHelperUtils.startPage().doSelectPageInfo(() -> userMapper.select(name,roleId,valid));
    }


    /**
     * 加密
     */
    private void encrypt(User user) {
        user.setSalt(UUID.randomUUID().toString());
        SimpleHash sh = new SimpleHash("MD5", user.getPassword(), user.getSalt(), 3);
        user.setPassword(sh.toHex());
    }
}
